#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/uaccess.h>

#define CHRDEVBASE_MAJOR 200			/* 主设备号 */
#define CHRDEVBASE_NAME	"chrdevbase"	/* 设备名 */

static char readbuf[100];	/* 读缓存 */
static char writebuf[100];	/* 写缓存 */
static char kerneldata[] = {"kernel data!"};

static int chrdevbase_open(struct inode *inode, struct file *filp);
static int chrdevbase_close(struct inode *inode, struct file *filp);
static ssize_t chrdevbase_read(struct file *filp, __user char *buf, size_t count, loff_t *ppos);
static ssize_t chrdevbase_write(struct file *filp, __user char *buf, size_t count, loff_t *ppos);
static int __init chrdevbase_init(void);
static void __exit chrdevbase_exit(void);

static struct file_operations chrdevbase_fops = {
	.owner = THIS_MODULE,
	.open = chrdevbase_open,
	.release = chrdevbase_close,
	.read = chrdevbase_read,
	.write = chrdevbase_write,
};

static int chrdevbase_open(struct inode *inode, struct file *filp)
{
	printk("chrdevbase_open\r\n");
	return 0;
}

static int chrdevbase_close(struct inode *inode, struct file *filp)
{
	printk("chrdevbase_release\r\n");
	return 0;
}

static ssize_t chrdevbase_read(struct file *filp, __user char *buf, size_t count, loff_t *ppos)
{
	int ret = 0;

	//printk("chrdevbase_read\r\n");
	/* 向用户空间发送数据 */
	memcpy(readbuf, kerneldata, sizeof(kerneldata));
	ret = copy_to_user(buf, readbuf, count);
	if(ret == 0) {
		printk("kernel senddata ok!\r\n");
	} else {
		printk("kernel senddata failed!\r\n");
	}
	return 0;
}
static ssize_t chrdevbase_write(struct file *filp, __user char *buf, size_t count, loff_t *ppos)
{
	int ret = 0;

	/* 接收用户空间传递给内核的数据并打印出来 */
	ret = copy_from_user(writebuf, buf, count);
	if(ret == 0) {
		printk("kernel recevdata:%s\r\n", writebuf);
	} else {
		printk("kernel recevdata failed!\r\n");
	}
	//printk("chrdevbase_write\r\n");
	return 0;
}

static int __init chrdevbase_init(void)
{
	int ret = 0;
	printk("chrdevbase_init\r\n");
	
	/* 注册字符设备 */
	ret = register_chrdev(CHRDEVBASE_MAJOR, CHRDEVBASE_NAME, &chrdevbase_fops);
	if(ret < 0) {
		printk("chrdevbase init failed!\r\n");
	}

	printk("chrdevbase init success!\r\n");

	return 0;
}

static void __exit chrdevbase_exit(void)
{
	printk("chrdevbase_exit\r\n");

	/* 注销字符设备 */
	unregister_chrdev(CHRDEVBASE_MAJOR, CHRDEVBASE_NAME);
	
}

/*
模块入口和出口
*/
module_init(chrdevbase_init);
module_exit(chrdevbase_exit);
